package gobase

import (
	"fmt"
	"os"
	"sync"
)

var (
	lk                 sync.Mutex
	fatalLogFileName   string
	initalFatalOutput  *os.File
	currentFatalOutput *os.File
)

func SetFatalWriteFile(filename string) error {
	_logFile, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	if err != nil {
		return err
	}
	err = RedirectStderr(_logFile, "SetFatalWriteFile:"+filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "[%s]SetFatalWriteFile>>RedirectStderr err:%s", NowString(), err.Error())
	} else {
		currentFatalOutput = _logFile
	}
	return err
}

func TestFatal() {
	var buf []byte
	buf[0] = 1
}

func CheckSetFatalLogFile(fileName string) {
	if fatalLogFileName != fileName {
		fatalLogFileName = fileName
		lk.Lock()
		defer lk.Unlock()

		realFileName := ParseFileName(fileName)
		if len(fileName) > 0 {
			_ = ForceCreateFilePath(realFileName)
			err := SetFatalWriteFile(realFileName)
			if err != nil {
				LogWarnPrintf("redirect Fatal file %s fail:%s", realFileName, err.Error())
			} else {
				LogPrintf("redirect Fatal file %s succ", realFileName)
			}
		} else {
			_ = RedirectStderr(initalFatalOutput, "")
			if currentFatalOutput != nil {
				currentFatalOutput.Close()
				currentFatalOutput = nil
			}
			LogWarnPrintf("redirect Fatal file default")
		}
	}
}

func init() {
	initalFatalOutput = os.Stderr
}
